import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/modle/person/bloc/select_money_to_yj_bloc.dart';
import 'package:shopping_group/modle/person/entity/money_order_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:bot_toast/bot_toast.dart';

class SelectMoneyJuanPage extends StatefulWidget {
  SelectMoneyJuanPage({
    Key key,
  }) : super(key: key);
  @override
  _SelectMoneyJuanPageState createState() => _SelectMoneyJuanPageState();
}

class _SelectMoneyJuanPageState extends State<SelectMoneyJuanPage> {
  List<MoneyOrderEntity> _listEntity = [];
  SelectMoneyToYjBloc _bloc;
  String _price = '0';
  @override
  void initState() {
    super.initState();
    _initSync();
  }

  void _initSync() {
    _bloc = SelectMoneyToYjBloc();
    Map<String, dynamic> data = {};
    data['val'] = BaseConstant.userId;
    _bloc.initDate.add(data);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '选择代理券'),
      body: Container(
        height: double.infinity,
        decoration: new BoxDecoration(
          color: Colours.title_white,
        ),
        child: Column(
          children: <Widget>[
            _titleView(),
            // _buildNotice(),
            Expanded(
              child: _gridView(),
            ),
            _bottomView(),
          ],
        ),
      ),
    );
  }

  Widget _titleView() {
    return Container(
      alignment: Alignment.center,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
      decoration: new BoxDecoration(
        color: Colours.blackground_black_239,
      ),
      child: WidgetUtils.getTextColorView(
          '您已拥有以下代理券，请选择要转成推广费的代理券（可多选）', Colors.white, Dimens.FONT_SIZE_14),
    );
  }

  Widget _bottomView() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(top: 4),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Container(
              alignment: FractionalOffset.center,
              height: 54,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  WidgetUtils.getTextColorView(
                      '总额：', Colors.white, Dimens.FONT_SIZE_14,
                      fontweight: FontWeight.w500),
                  WidgetUtils.getTextColorView(
                      _price, Colours.themeColor, Dimens.FONT_SIZE_14,
                      fontweight: FontWeight.w500),
                ],
              ),
              decoration: BoxDecoration(
                // borderRadius: BorderRadius.circular(10),
                color: Colours.blackground_black_239,
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                if ('0' == _price) {
                  BotToast.showText(text: '请选择一个代理券');
                  return;
                }
                List<String> idList = [];
                _listEntity.forEach((element) {
                  if (element.isSelect) {
                    idList.add(element.id);
                  }
                });
                Map<String, dynamic> data = {};
                data['userId'] = BaseConstant.userId;
                data['lstMoId'] = idList;
                _bloc.changeDate.add(data);
              },
              child: Container(
                alignment: FractionalOffset.center,
                height: 54,
                child: WidgetUtils.getTextColorView(
                    '转推广费', Colors.white, Dimens.FONT_SIZE_14,
                    fontweight: FontWeight.w500),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(10),
                  color: Colours.text_9C1,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _gridView() {
    return StreamBuilder(
      stream: _bloc.sendData,
      initialData: _listEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is List) {
          _listEntity = object;
        }

        return Container(
          // margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),

          // margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
          child: GridView.builder(
              itemCount: _listEntity.length,

              //SliverGridDelegateWithFixedCrossAxisCount 构建一个横轴固定数量Widget
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  //横轴元素个数
                  crossAxisCount: 2,
                  //纵轴间距
                  mainAxisSpacing: 4.0,
                  //横轴间距
                  crossAxisSpacing: 16.0,

                  //子组件宽高长度比例
                  childAspectRatio: 0.75),
              itemBuilder: (BuildContext context, int index) {
                //Widget Function(BuildContext context, int index)

                return getItemContainer(_listEntity[index]);
              }),
        );
      },
    );
  }

  Widget getItemContainer(MoneyOrderEntity entity) {
    return GestureDetector(
      onTap: () {
        setState(() {
          entity.isSelect = !entity.isSelect;
          _price = '0';
          _listEntity.forEach((element) {
            if (element.isSelect) {
              _price = Utils.formatNum(
                  (double.parse(_price) + double.parse(element.shopAllPrice)),
                  2);
            }
          });
        });
      },
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
        alignment: Alignment.center,
        child: Material(
          borderRadius: BorderRadius.circular(4.0),
          color: entity.isSelect ? Colours.themeColor : Colours.title_white,
          // elevation: 5.0,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                height: 110.0,
                width: 110.0,
                margin: const EdgeInsets.all(5.0),
                child: FadeInImage.assetNetwork(
                  image:
                      'https://lizhengyouxuan.oss-cn-shanghai.aliyuncs.com/lizhengyouxuan/commSpec/xianjinjuan.png',
                  placeholder: 'images/picture_loading.png' /* 指定gif */,
                  fit: BoxFit.contain,
                ),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    margin: const EdgeInsets.only(left: 12, top: 12),
                    child: WidgetUtils.getTextMaxLinesView(
                        entity.name, Colours.text_2222, Dimens.FONT_SIZE_14,
                        overflow: TextOverflow.ellipsis),
                  ),
                  SizedBox(
                    height: 4,
                  ),
                  Container(
                    margin: const EdgeInsets.only(left: 12, bottom: 10),
                    child: WidgetUtils.getTextColorView(
                        '价格:${entity.shopAllPrice}',
                        Colours.main_01,
                        Dimens.FONT_SIZE_16,
                        textAlign: TextAlign.start,
                        fontweight: FontWeight.w500),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
